﻿using System;
using System.Web;
using eBlog.Entity;
using DBScript;
using eBlog.Service;
using eBlog.Common.Security;

namespace eBlog.Web.Ajax
{
    public partial class Comment : System.Web.UI.Page
    {
        IDBBase dal = DBFactory.GetDbProvider();

        protected void Page_Load(object sender, EventArgs e)
        {
           
            var tid = Request.Form["tid"];
            var author = Request.Form["author"];
            var url=Request.Form["url"];
            if (!string.IsNullOrEmpty(url))
            {
               url=url.ToLower().Replace("http://", " ").Trim();
            }
            else
            {
                url = "www.vsmvp.com";
            }
            //var email = Request.QueryString["email"];
            var content = Request.Form["content"];
            addComment(tid, author,url, content);
        }


        public void addComment( string tid,string author,string url,string content)
        {
            int result = 0;
            if(!string.IsNullOrEmpty(author)&&!string.IsNullOrEmpty(content))
            {
                Comments comment=new Comments();
                comment.Content = content;
                comment.Name = author;
                comment.SiteUrl =url;
                comment.CreateDate = DateTime.Now;
                comment.ParentID = 0;
                comment.TargetID = int.Parse(tid);
                comment.Staus = 1;

                result= dal.Add(comment);
                
                //记录cookie
                HttpCookie UserCookie = new HttpCookie("User");
               // UserCookie["id"] = isSuccess.ToString();
                UserCookie["name"] = Server.UrlEncode(comment.Name);
                UserCookie["url"] = Server.UrlEncode(comment.SiteUrl);
                UserCookie["key"] = MD5.FormatCookie(comment.Name);
                UserCookie.Expires = DateTime.Now.AddMinutes(300);
                Response.Cookies.Add(UserCookie);

               

            }
            if(result>0)
            {
                
                //更新文章评论数
                var postModel = dal.GetModel<Posts>(int.Parse(tid));
                postModel.CommentCount = postModel.CommentCount + 1;
                dal.Update(postModel);

                //更新统计数
                StatisticsService.UpdateStatisticsPostCount(1);

                     Response.Write("{ isSuccess: true,  returnMessage: \"恭喜您，留言成功！\"}");
            }
            else
            {
                Response.Write("{ isSuccess: false,  returnMessage: \"留言失败，请稍后再试！\"}");
            }
            
          
        }
    }
}